package basic.practice;

import java.sql.SQLException;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 
 * @author 42276
 * @author 任雪燕
 * @author 24372
 * @author 15869
 * @author admin
 * @author 张冰锋
 * @author 清风依旧 
 * Consumers of message-oriented middleware
 */

public class Consumer {
	static StudentManagerImpl si = new StudentManagerImpl();
	static Student stu = new Student();

	// 定义ActivMQ的连接地址
	private static final String ACTIVEMQ_URL = "tcp://127.0.0.1:61616";
	// 定义发送消息的队列名称
	private static final String QUEUE_NAME = "MessageFromPlaidShirt";// MyMessage

	public void MessageReceive() throws JMSException {
		// 创建连接工厂
		ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
		// 创建连接
		Connection connection = activeMQConnectionFactory.createConnection();
		// 打开连接
		connection.start();
		// 创建会话
		Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		// 创建队列目标
		Destination destination = session.createQueue(QUEUE_NAME);
		// 创建消费者
		javax.jms.MessageConsumer consumer = session.createConsumer(destination);
		// 创建消费的监听
		consumer.setMessageListener(new MessageListener() {
			@Override
			public void onMessage(Message message) {
				TextMessage textMessage = (TextMessage) message;
				try {
					System.out.println("Message Receiving：" + textMessage.getText());
					String tempString = textMessage.getText();
//    	        	将记录添加到数据库
					String[] s = tempString.split("\\s+");

					stu.setId(s[0]);
					stu.setName(s[1]);
					stu.setSex(s[2]);
					stu.setTel(s[3]);
					try {
						si.add(stu);
					} catch (SQLException e) {

						e.printStackTrace();
					}
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
		});
	}
}
